package com.bw.title.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.po.TbHouseMessage;
import com.bw.po.TbResource;
import com.bw.result.ResponseState;
import com.bw.result.ResultVo;
import com.bw.title.service.TbHouseMessageService;
import com.bw.title.service.TbResourceService;
import com.bw.util.SnowflakeIdWorker;
import com.bw.vo.IdVo;
import com.bw.vo.TbMessageVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.Date;


@RestController
@Slf4j
@RequestMapping("/title")
public class TbHouseMessageController {

    @Autowired
    private TbHouseMessageService tbHouseMessageService;

    @Autowired
    private TbResourceService tbResourceService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0,0);

    /**
     * 添加资讯信息
     * @param tbMessageVo
     * @return
     */
    @PostMapping("/houseMessageAdd")
    public ResultVo houseMessageAdd(@RequestBody TbMessageVo tbMessageVo) {
        //使用雪花算法随机生成资讯的ID
        tbMessageVo.setId(String.valueOf(idWorker.nextId()));
        //生成创建日期为当前日期
        tbMessageVo.setPublishTime(new Date());
        //生成默认状态
        tbMessageVo.setStatus(0);
        //默认访问次数设置为0
        tbMessageVo.setPageView(0);
        //redis获取图片信息的UUID
        String resourceId = redisTemplate.opsForValue().get("tbResource -> resourceId：");
        //判断resourceId是在redis中存在
        if (StringUtils.isNotEmpty(resourceId)){
            //获取图片关联ID
            tbMessageVo.setResourceId(resourceId);
        }else {
            //返回错误信息
            return ResultVo.FAILED(ResponseState.INSERT_ERROR);
        }
        //判断资讯标题是否存在
        if (StringUtils.isEmpty(tbMessageVo.getHeadline())){
            return ResultVo.FAILED(ResponseState.DATA_DO_NOT_NULL);
        }
        //判断详情内容是否存在
        if (StringUtils.isEmpty(tbMessageVo.getContent())){
            return ResultVo.FAILED(ResponseState.DATA_DO_NOT_NULL);
        }
        //判断创建人是否存在
        if (StringUtils.isEmpty(tbMessageVo.getCreatedBy())){
            return ResultVo.FAILED(ResponseState.DATA_DO_NOT_NULL);
        }
        //创建实体类对象
        TbHouseMessage tbHouseMessage = new TbHouseMessage();
        //将VO存储的值拷贝到实体类
        BeanUtils.copyProperties(tbMessageVo,tbHouseMessage);
        //添加信息，并返回成功与失败
        boolean save = tbHouseMessageService.save(tbHouseMessage);
        //提示正确与错误信息
        if (save){
            //清除redis缓存
            redisTemplate.delete("tbResource -> resourceId：");
            return ResultVo.SUCCESS();
        }else {
            return ResultVo.FAILED(ResponseState.INSERT_ERROR);
        }
    }

    /**
     *编辑资讯
     * @param tbMessageVo
     * @return
     */
    @PostMapping("/updateTitleMessage")
    public ResultVo updateTitleMessage(@RequestBody TbMessageVo tbMessageVo){
        //获取将要修改的数据
        TbHouseMessage houseMessage = tbHouseMessageService.getById(tbMessageVo.getId());
        //获取旧图片的resourceId
        String oldResourceId = houseMessage.getResourceId();
        //用queryWrapper创建将要引用的数据
        LambdaQueryWrapper<TbResource> queryWrapper = new LambdaQueryWrapper<>();
        //引用ResourceId
        queryWrapper.eq(TbResource::getResourceId,oldResourceId);
        //删除旧的图片信息
        boolean remove = tbResourceService.remove(queryWrapper);
        if (remove == false){
            return ResultVo.FAILED(ResponseState.DELETE_ERROR);
        }
        //redis获取新的图片ResourceId
        String newResourceId = redisTemplate.opsForValue().get("tbResource -> resourceId：");
        //判断resourceId是在redis中存在
        if (StringUtils.isNotEmpty(newResourceId)){
            //获取新的图片关联ID
            tbMessageVo.setResourceId(newResourceId);
        }else {
            //返回错误信息
            return ResultVo.FAILED(ResponseState.INSERT_ERROR);
        }
        //将VO对象拷贝到实体类
        BeanUtils.copyProperties(tbMessageVo,houseMessage);
        //修改信息
        boolean updateById = tbHouseMessageService.updateById(houseMessage);
        //判断修改的信息是否正确，并将正确和错误信息进行返回
        if (updateById){
            //清空redis缓存
            redisTemplate.delete("tbResource -> resourceId：");
            return ResultVo.SUCCESS();
        }else {
            return ResultVo.FAILED(ResponseState.UPDATE_ERROR);
        }
    }


    /**
     * 删除资讯
     * @param idVo
     * @return
     */
    @PostMapping("/delete")
    public ResultVo delete(@RequestBody IdVo idVo){
        //根据ID删除信息
        boolean removeById = tbHouseMessageService.removeById(idVo.getId());
        //判断删除的信息是否正确，并将正确和错误信息进行返回
        if (removeById){
            return ResultVo.SUCCESS();
        }else {
            return ResultVo.FAILED(ResponseState.DELETE_ERROR);
        }
    }

    /**
     * 查询资讯列表（资讯名称模糊查询+状态条件查询）
     * @param tbMessageVo
     * @return
     */
    @PostMapping("/houseMessage")
    public ResultVo houseMessage(@RequestBody TbMessageVo tbMessageVo){
        return tbHouseMessageService.houseMessage(tbMessageVo);
    }

    /**
     * 根据id查看资讯详情信息
     * @param idVo
     * @return
     */
    @PostMapping("/titleById")
    public ResultVo titleById(@RequestBody IdVo idVo){
        return tbHouseMessageService.titleById(idVo);
    }

    /**
     * 根据ID修改资讯状态
     * @param tbMessageVo
     * @return
     */
    @PostMapping("updateByStatus")
    public ResultVo updateByStatus(@RequestBody TbMessageVo tbMessageVo){
        return tbHouseMessageService.updateByStatus(tbMessageVo);
    }


}
